<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/16
 * Time: 15:43
 */
require_once '../Redis.php';

// 令牌桶设计概念 接口限流设计
class TokenRedis
{

    public $container = 'token'; //redis list 容器名称

    public $max = 20; //容器最大值

    // 增加令牌
    public function addToken($num = 0)
    {
        $size = Rediss::lSize($this->container);//获取容器剩余数量
        $max = (int)$this->max;//获取最大长度
        //获取需要添加的数量
        $addNum = $max >= $size + $num ? $num : $max - $size;
        $addArray = array_fill(0, $addNum, 1);
        if ($addNum > 0) {
            foreach ($addArray as $v) {
                Rediss::lpush($this->container, $v);
            }
            return $num;
        }
        return 0;
    }

//    减少令牌
    public function reduceToken()
    {
        $res = Rediss::rpop($this->container);
        return $res;
    }


    //重置
    public function reset()
    {
        Rediss::del($this->container);
        $this->addToken($this->max);
    }

}